package com.etc.controller;

import com.etc.entity.Travels;
import com.etc.service.TravelsService;
import com.etc.util.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by Administrator on 2019/5/25.
 */
@Controller
@RequestMapping("/news")
public class UeditorController {

    @Autowired
    private TravelsService travelsService;
    @Autowired
    private Message msg;

    @RequestMapping(value = "/addNews.do", method = RequestMethod.POST)
    @ResponseBody
    public Message addNews(Travels travels) {

        boolean flag=travelsService.insertSelective(travels);
        msg.setMsg("发布失败");
        if (flag) {
            msg.setMsg("发布成功");
        }

        return msg;
    }


    @RequestMapping("/upload.do")
    @ResponseBody
    public Map<String, String> uploadimage(@RequestParam(value = "upfile") MultipartFile upfile) {
        Map<String, String> map = new HashMap<>();
        String fileName = upfile.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String filename = sdf.format(new Date()) + new Random().nextInt(1000);
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        filename = filename + "." + fileExt;//存入虚拟目录后的文件名
        File uploadedFile = new File("D:\\apache-tomcat-8.5.13\\webapps\\file1\\img", filename);//存入虚拟目录后的文件
        try {
            upfile.transferTo(uploadedFile);//上传
            map.put("url", "/img/" + filename);//这个url是前台回显路径（回显路径为config.json中的imageUrlPrefix+此处的url）
            map.put("state", "SUCCESS");
            map.put("original", "");
        } catch (IllegalStateException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }


}
